<template>
  <el-select ref="select" v-model="selectNode.departmentName" placeholder="请选择">
    <el-option :value="selectNode.id" :label="selectNode.departmentName" style="height: auto;width: auto">
      <el-tree
        ref="combotree"
        :data="treeData"
        :props="defaultProps"
        :expand-on-click-node="false"
        @node-click="handleNodeSelected">
      </el-tree>
    </el-option>
  </el-select>
</template>

<script>
  import departmentApi from '@/api/department';
  export default {
    //获取父组件传过来的值
    props:{
      parentNode:{}
    },
    name: "combotree",
    created() {
        this.getTreeData();
        this.selectNode = this.parentNode;
    },
    data(){
          return{
            //combotree数据
            treeData: [],
            selectNode: {},
            defaultProps: {
              children: 'children',
              label: 'departmentName',
              value: 'id'
            }
          }
      },
    //监听父组件传过来的值是否改变以刷新数据，不然只在created时接受父组件的值的话以后不会再刷新子组件数据。
    watch:{
      parentNode(n,o){
        this.selectNode = n;
      }
    },
    methods:{
        async getTreeData(){
          let res = await departmentApi.getDepartmentTree();
          if(res.code == 200){
            this.treeData = res.data;
          }
        },
        handleNodeSelected(){
          let selectNode = this.$refs.combotree.getCurrentNode();
          this.selectNode = selectNode;
          //选中节点的数据传给父页面
          this.$emit('combotreeNodeSelected',selectNode);
          // combotree选中条目后处理一下，让panel收起来
          this.$refs.select.blur();
        }
      }
  }
</script>

<style scoped>

</style>
